//
//  RegisterVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/12.
//

import UIKit

class RegisterVC: BaseVC {

    
    private var times: Int = 0
    var timer: Timer?
    @IBOutlet weak var loginBtn: UIButton! //验证码登录
    @IBOutlet weak var accView: UIView!
    @IBOutlet weak var pwdView: UIView!
    @IBOutlet weak var pwd2View: UIView!
    @IBOutlet weak var codeView: UIView!
    @IBOutlet weak var loginSendCodeBtn: UIButton! //获取验证码
    
    @IBOutlet weak var accountTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var registerConfirmTextField: UITextField!
    @IBOutlet weak var registerCodeTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        
        accView.layer.cornerRadius = 10
        accView.layer.borderWidth = 1
        accView.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).cgColor
        
        pwdView.layer.cornerRadius = 10
        pwdView.layer.borderWidth = 1
        pwdView.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).cgColor
        
        pwd2View.layer.cornerRadius = 10
        pwd2View.layer.borderWidth = 1
        pwd2View.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).cgColor
        codeView.layer.cornerRadius = 10
        codeView.layer.borderWidth = 1
        codeView.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).cgColor
        
        loginBtn.layer.cornerRadius = 10
        loginSendCodeBtn.layer.cornerRadius = 10
    }

    @IBAction func back(_ sender: Any) {
        dismiss(animated: true)
    }
    
    // 注册 发送验证码
    @IBAction func getCode(_ sender: Any) {//获取验证码
        guard let accountText = accountTextField.text, !accountText.isEmpty else {
            MHAlert.showMessage("InputAccnout".localized())
            return
        }

        guard isValidPhoneNumber(phoneNumber: accountText) else {
            MHAlert.showMessage( "AccountError".localized())
            return
        }

        SVProgressHUD.show()
        Task {
            let (res, err) = await gosnLogin.getCode(accountText,1)
            await MainActor.run {
                SVProgressHUD.dismiss()
                if let err = err {
                    let errMessage = "\(err.description)"
                    MHAlert.showMessage(errMessage)
                }else {
                    DispatchQueue.main.async {
                        MHAlert.showMessage(KLocalizedString("CodeSendSuccess"))
                        self.changeSendCodeStatus()
                    }
                }
            }
        }
    }
    
    func changeSendCodeStatus() {
        times = 60
        loginSendCodeBtn!.endEditing(false)
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
//        Timer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }
    
    @objc func timerAction() {
        times -= 1
        loginSendCodeBtn!.setTitle("(\(times)s)", for: .normal)
        
        if times <= 0 {
            timer?.invalidate()
            timer = nil
            loginSendCodeBtn.setTitle(NSLocalizedString("SendCodeBtnText", comment: ""), for: .normal)
            loginSendCodeBtn.isEnabled = true
        }
    }

    // 假设 registerNewUser 是一个按钮点击事件的处理函数
    @IBAction func register(_ sender: Any) {
        guard let accountText = accountTextField.text, !accountText.isEmpty else {
            MHAlert.showMessage(KLocalizedString("InputAccnout"))
            return
        }
        
        if !isValidPhoneNumber(phoneNumber: accountText) {
            MHAlert.showMessage(KLocalizedString("AccountError"))
            return
        }
        
        guard let passwordText = passwordTextField.text, !passwordText.isEmpty else {
            MHAlert.showMessage(KLocalizedString("InputSetingPwd"))
            return
        }
        
        if registerConfirmTextField.text != passwordText {
            MHAlert.showMessage(KLocalizedString("InputConfirmPwd"))
            return
        }
        
        guard let codeText = registerCodeTextField.text, !codeText.isEmpty else {
            MHAlert.showMessage(KLocalizedString("InputCode"))
            return
        }
        SVProgressHUD.show()
        Task {
            let (res, err) = await gosnLogin.register(accountText, passwordText, codeText)
            await MainActor.run {
                SVProgressHUD.dismiss()
                if let err = err {
                    MHAlert.showMessage("\(err)")
                }else{
                    MHAlert.showMessage(KLocalizedString("RegisterSuccess"))
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        self.dismiss(animated: true)
                    }
                }
            }
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}
